package org.demo.xsd;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.Set;

import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.sun.xml.xsom.XSComplexType;
import com.sun.xml.xsom.XSSchema;
import com.sun.xml.xsom.parser.SchemaDocument;
import com.sun.xml.xsom.parser.XSOMParser;

/**
 * 
 * @author  
 * @date    2011-1-24
 * @file    org.demo.xsd.SchemaUtil.java
 */
public class SchemaUtil {
	
	private static final String XSD_NS_BO = "http://www.loushang.org/xmlns/prod/bo/6.0.0";
	private static final String XSD_NS_JDBCASI = "http://www.loushang.org/xmlns/prod/j2ca/jdbc/metadata";
	private static String resource_dir = null;
	
	static {
		resource_dir = System.getProperty("user.dir") + "/resources";
	}
	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		String path = "D:/workspace/eclipse_inspur/adapter_config_pro/WebContent/WEB-INF/ra/I_SPYW_APPLIANCE_SELFCHECK/I_SPYW_APPLIANCE_SELFCHECKBG.xsd";
		
		// 
		SchemaUtil t = new SchemaUtil();
		XSSchema schema = t.loadXSDSchema(path);
		t.analyseSchema(schema);
	}
	/**
	 * 加载 Schema
	 * @param filePath
	 * @return
	 * @throws Exception
	 */
	public XSSchema loadXSDSchema(String filePath) throws Exception{
		
		XSOMParser parser = new XSOMParser();
		
		// 处理所引用的外部 schema
		parser.setEntityResolver(new EntityResolver(){
			@Override
			public InputSource resolveEntity(String publicId, String systemId)
					throws SAXException, IOException {
				String path = null;
				if (XSD_NS_BO.equals(publicId)){
					path = resource_dir + "/BusinessGraph.xsd";
				} else if (XSD_NS_JDBCASI.equals(publicId)){
					path = resource_dir + "/JDBCASI.xsd";
				}
				InputSource source = null;
				if (path != null){
					source = new InputSource(new FileInputStream(path));
					source.setPublicId(publicId);
					source.setSystemId(systemId);
				}
				return source;
			}
		});
		
		// 解析当前文件
		URL url = new File(filePath).toURI().toURL();		
		parser.parse(url);
		parser.getResult();
		
		// 查找当前文件对应的 Schema
		XSSchema schema = null;
		String currentSystemId = url.toExternalForm();
		Set<SchemaDocument> docs = parser.getDocuments();
		for (SchemaDocument doc : docs){
			if (currentSystemId.equals(doc.getSystemId())){
				schema = doc.getSchema();
			}
		}
		return schema;
	}
	/**
	 * 分析整个 schema
	 * @param schema
	 */
	public void analyseSchema(XSSchema schema){
		Map<String,XSComplexType> comp_map = schema.getComplexTypes();
		Set<String> keys = comp_map.keySet();
		XSComplexType type = null;
		for (String key : keys){
			type = comp_map.get(key);
			// 输出当前元素名称
			System.out.println(type.getName());
			type.visit(new ElementVistor(1));			
		}
	}
}
